<template>
	<view>
		<scan></scan>
		<scanner></scanner>
		<sm></sm>
		<honeywell></honeywell>
		<button @click="searchBle">搜索蓝牙</button>
		<button @click="getWeight">获取重量</button>
		<view class="content wrap">
			<u-form :model="form" ref="uForm" >
				<u-form-item label="订单号:" label-width="150" prop="orderNo">
					<u-row>
						<u-col span="11" text-align="center">
							<u-input v-model="form.orderNo" placeholder="请输入订单号" />
						</u-col>
						<u-col span="1" text-align="center" style="display: flex; align-items: center;" @click="scan">
							<u-icon name="scan" color="#2b85e4" size="43" style="font-size: 80px;">手机扫描</u-icon>
						</u-col>
					</u-row>
				</u-form-item>
				<u-form-item label="标准重量:" label-width="150" prop="goodWeight">
					<u-row>
						<u-col span="11" text-align="center">
							<u-input type="number" v-model="form.goodWeight" placeholder="请输入标准重量" />
						</u-col>
						<u-col span="1" text-align="center" style="display: flex; align-items: center;" @click="ddzl">
							<u-icon name="https://s21.ax1x.com/2024/05/29/pk39yRI.png" color="#0000ff" size="43" style="font-size: 80px;">单重</u-icon>
						</u-col>
					</u-row>
				</u-form-item>
				<u-form-item label="包材重量:" label-width="150" prop="boxWeight">
					<u-row>
						<u-col span="11" text-align="center">
							<u-input type="number" v-model="form.boxWeight" placeholder="请输入包材重量"/>
						</u-col>
						<u-col span="1" text-align="center" style="display: flex; align-items: center;"@click="scan1">
						  <u-icon name="scan" color="#2b85e4" size="43" style="font-size: 80px;">手机扫描</u-icon>
						</u-col>
					</u-row>
				</u-form-item>
				<u-form-item label="预警上浮:" label-width="150" prop="warnUp">
					<u-row>
						<u-col span="11" text-align="center">
							<u-input type="number" v-model="form.warnUp" placeholder="请输入预警上浮" />
						</u-col>
					</u-row>
				</u-form-item>
				<u-form-item label="预警下浮:" label-width="150" prop="warndown">
					<u-row>
						<u-col span="11" text-align="center">
							<u-input type="number" v-model="form.warndown" placeholder="请输入预警下浮" />
						</u-col>
					</u-row>
				</u-form-item>
				<u-form-item label="实际重量:" label-width="150" prop="realWeight">
					<u-row>
						<u-col span="11" text-align="center">
							<u-input class="uni-input font-80" type="number" v-model="form.realWeight" disabled placeholder="请输入实际重量" />
						</u-col>
					</u-row>
				</u-form-item>
				<u-form-item label="自动校验:" label-width="150" prop="autoCnt">
					<u-row>
						<u-col span="11" text-align="center">
							<u-input class="uni-input font-80" type="number" v-model="form.autoCnt"  placeholder="请输入自动数" />
						</u-col>
					</u-row>
				</u-form-item>
			</u-form>
		</view>
		<button @click="jiaoyan" type="primary" >校验</button>
		<view style="margin-top: 2upx;" :key="index" v-for="(item,index) in devices">
			<button style="width: 400upx; color: #0081FF;" @click="onConn(item)">{{item.name}}</button>
		</view>
	</view>

</template>


<script>
	import scan from "@/components/uni-scan/scan.vue"
	import scanner from "@/components/uni-scan/scanner.vue"
	import sm from "@/components/uni-scan/sm.vue"
	import honeywell from "@/components/uni-scan/honeywell.vue"
	import radio from "@/components/uni-scan/radio.js"
	export default {
		components: {
			scanner,
			scan,
			sm,
			honeywell
		},
		data() {
			return {
				realWeightCnt:0,
				form:{
					goodWeight:0,
					boxWeight:0,
					warnUp:0,
					warndown:0,
					realWeight:0,
					orderNo:'',
					boxCode:'',
					autoCnt:5
				},
				devices: [],
				currDev: null,
				connId: '',
				piaojuText: '',
				tableDomId: '',
				tableImgPath: '',
				canvasWidth: 800,
				canvasHeight: 600,
				msg: '',
				www: 0.00,
				deviceId:''
			}
		},
		onShow() {
			let orderNoScan = false;
			let boxCodeScan = false;
			
			uni.$off('scan');
			uni.$on('scan', (res) => {
				if (!orderNoScan) {
					orderNoScan = true;
					if (boxCodeScan) {
						boxCodeScan = false; // 如果this.form.tarPositionCode已经被赋值过，则将它的标志重置
					}
					this.form.orderNo=res.codeStr;
					this.selectByOrderNo();
				} else if (!boxCodeScan) {
					boxCodeScan = true;
					if (orderNoScan) {
						orderNoScan = false; // 如果this.form.srcPositionCode已经被赋值过，则将它的标志重置
					}
					this.form.boxCode = res.codeStr;
					this.selectByBoxCode();
				}
				
			});
			uni.$off('scanner') // 每次进来先 移除全局自定义事件监听器
			uni.$on('scanner', (res) => {
				if (!orderNoScan) {
					orderNoScan = true;
					if (boxCodeScan) {
						boxCodeScan = false; // 如果this.form.tarPositionCode已经被赋值过，则将它的标志重置
					}
					this.form.orderNo=res.codeStr;
					this.selectByOrderNo();
				} else if (!boxCodeScan) {
					boxCodeScan = true;
					if (orderNoScan) {
						orderNoScan = false; // 如果this.form.srcPositionCode已经被赋值过，则将它的标志重置
					}
					this.form.boxCode = res.codeStr;
					this.selectByBoxCode();
				}
			})
			uni.$off('sm') // 每次进来先 移除全局自定义事件监听器
			uni.$on('sm', (res) => {
				if (!orderNoScan) {
					orderNoScan = true;
					if (boxCodeScan) {
						boxCodeScan = false; // 如果this.form.tarPositionCode已经被赋值过，则将它的标志重置
					}
					this.form.orderNo=res.codeStr;
					this.selectByOrderNo();
				} else if (!boxCodeScan) {
					boxCodeScan = true;
					if (orderNoScan) {
						orderNoScan = false; // 如果this.form.srcPositionCode已经被赋值过，则将它的标志重置
					}
					this.form.boxCode = res.codeStr;
					this.selectByBoxCode();
				}
			})
			uni.$off('honeywell') // 每次进来先 移除全局自定义事件监听器
			uni.$on('honeywell', (res) => {
				if (!orderNoScan) {
					orderNoScan = true;
					if (boxCodeScan) {
						boxCodeScan = false; // 如果this.form.tarPositionCode已经被赋值过，则将它的标志重置
					}
					this.form.orderNo=res.codeStr;
					this.selectByBoxCode();
				} else if (!boxCodeScan) {
					boxCodeScan = true;
					if (orderNoScan) {
						orderNoScan = false; // 如果this.form.srcPositionCode已经被赋值过，则将它的标志重置
					}
					this.form.boxCode = res.codeStr;
					this.selectByBoxCode();
				}
			})
		},
		onUnload() { // 离开断开蓝牙
			this.closeBLEConnection();
			uni.showLoading({
				title: '断开蓝牙',
			});
			setTimeout(function() {
				uni.hideLoading();
			}, 1000);
		},
		watch: {
			realWeightCnt(newVal, oldVal) {
				if(this.form.autoCnt <= 0 ){
					return;
				}
				if(this.realWeightCnt === this.form.autoCnt ){
					this.jiaoyan();
				}
			}
		},
		onReady() {
		},
		methods: {
			wd(newVal,oldVal){
				if(this.form.autoCnt <= 0 ){
					return;
				}
				if(this.form.orderNo != ''){
					return;
				}
				
				if(newVal <= 0 ){
					this.realWeightCnt = 0;
					return;
				}
				
				if(newVal != oldVal){
					this.realWeightCnt = 0;
				}else{
					this.realWeightCnt = this.realWeightCnt + 1;
					if(this.realWeightCnt > this.form.autoCnt){
						this.realWeightCnt = this.form.autoCnt + 100;
					}
				}
			},
			scan() {
				uni.scanCode({
					success: (res) => {
						this.form.orderNo=res.result;
						this.selectByOrderNo();
					}
				});
			},
			scan1() {
				uni.scanCode({
					success: (res) => {
						this.form.boxCode = res.codeStr;
						this.selectByBoxCode();
					}
				});
			},
			ddzl(){
				// 判断称重重量
				if(this.form.orderNo == ''){
					uni.showToast({
						title: '请输入订单号后进行操作！！！',
						duration: 2000,
						icon:'none',
					});
					return false;
				}
				this.selectByOrderNo();
			},
			jiaoyan(){
				// 判断称重重量
				if(this.form.realWeight < 1){
					uni.showToast({
						title: '未获取到实际重量',
						duration: 2000,
						icon:'none',
					});
					//失败音响
					radio.play_ding_fail();
					return false;
				}
				// 判断标准重量
				if(this.form.goodWeight < 1){
					uni.showToast({
						title: '未获取到标准重量',
						duration: 2000,
						icon:'none',
					});
					//失败音响
					radio.play_ding_fail();
					return false;
				}
				let weight1 = Number(this.form.boxWeight) + Number(this.form.goodWeight);
				let weightMax = Number(weight1) + Number(this.form.warnUp);
				let weightMin = Number(weight1) - Number(this.form.warndown);
				
				if(this.form.realWeight < weightMin){
					uni.showToast({
						title: '重量已超下限，复核不通过',
						duration: 2000,
						icon:'none',
					});
					//失败音响
					radio.play_ding_fail();
					return false;
				}
				
				if(this.form.realWeight > weightMax){
					uni.showToast({
						title: '重量已超上限，复核不通过',
						duration: 2000,
						icon:'none',
					});
					//失败音响
					radio.play_ding_fail();
					return false;
				}
				uni.showToast({
					title: '复核通过',
					duration: 2000,
					icon:'none',
				});
				// 成功声音
				radio.play_ding_success();
				// 复核成功后回传重量
				this.$http.post('/rest/orderWeightCheck/updateCheckWeightByOrderNo',{}, {
					params: {"orderNo":this.form.orderNo,"checkWeight":this.form.realWeight},
					header: {
						'Authorization': uni.getStorageSync('token'),
					}
				}).then(res => {
					uni.hideLoading()
					if (res.data.code == 200) {
						console.log("回传成功")
					}
				})
			},
			selectByOrderNo(){
				uni.showLoading({
						title: '正在处理'
				})
				// this.form.goodWeight = 0;
				this.$http.post('/rest/orderWeightCheck/findByOrderNo',{}, {
					params: {"orderNo":this.form.orderNo},
					header: {
						'Authorization': uni.getStorageSync('token'),
					}
				}).then(res => {
					uni.hideLoading()
					if (res.data.code == 200) {
						this.form.goodWeight = res.data.data.weight;
						this.jiaoyan();
					}else{
						this.form.goodWeight = 0;
						uni.showToast({
							title: res.data.message,
							duration: 2000,
							icon:'none',
						});
					}
				})
			},
			selectByBoxCode(){
				uni.showLoading({
						title: '正在处理'
				})
				// this.form.goodWeight = 0; 
				this.$http.post('/rest/orderBoxWeight/findByBoxCode',{}, {
					params: {"boxCode":this.form.boxCode},
					header: {
						'Authorization': uni.getStorageSync('token'),
					}
				}).then(res => {
					uni.hideLoading()
					if (res.data.code == 200) {
						this.form.boxWeight = res.data.data.weight;
						this.jiaoyan();
					}else{
						this.form.boxWeight = 0;
						uni.showToast({
							title: res.data.message,
							duration: 2000,
							icon:'none',
						});
					}
				})
			},
			searchBle() {
				var that = this
				that.devices = [];
				uni.openBluetoothAdapter({
					success(res) {
						that.onDevice()
						uni.getBluetoothAdapterState({
							success: function(res) {
								if (res.available) {
									if (res.discovering) {
										that.stopFindBule()
									}
									console.log("开始搜寻附近的蓝牙外围设备")
									uni.startBluetoothDevicesDiscovery({
										success(res) {
											// console.log(res)
										}
									})
								} else {
									console.log('本机蓝牙不可用')
								}
							},
						})
					}
				})
			},
			onDevice() {
				// console.log("监听寻找到新设备的事件---------------")
				var that = this
				//监听寻找到新设备的事件
				uni.onBluetoothDeviceFound(function(devices) {
					var re = JSON.parse(JSON.stringify(devices))
					// console.log(re.devices[0].name + "  " + re.devices[0].deviceId)
					let name = re.devices[0].name
					if (name != "未知设备") {
						let deviceId = re.devices[0].deviceId
						that.devices.push({
							name: name,
							deviceId: deviceId,
							services: []
						})
					}
				})
			},
			stopFindBule() {
				// console.log("停止搜寻附近的蓝牙外围设备---------------")
				uni.stopBluetoothDevicesDiscovery({
					success(res) {
						// console.log(res)
					}
				})
			},
			hexCharCodeToStr(hexCharCodeStr) {
				var trimedStr = hexCharCodeStr.trim();
				var rawStr = trimedStr.substr(0, 2).toLowerCase() === "3d" ? trimedStr.substr(2) : trimedStr;
				var len = rawStr.length;
				if (len % 2 !== 0) {
					alert("存在非法字符!");
					return "";
				}
				var curCharCode;
				var resultStr = [];
				for (var i = 0; i < len; i = i + 2) {
					curCharCode = parseInt(rawStr.substr(i, 2), 16);
					resultStr.push(String.fromCharCode(curCharCode));
				}
				return resultStr.reverse().join("");
			},
			buf2hex(buffer) { // buffer is an ArrayBuffer
				return Array.prototype.map.call(new Uint8Array(buffer), x => ('00' + x.toString(16)).slice(-2)).join('');
			},
			onConn(item) {
				var that = this
				// console.log("连接蓝牙---------------" + item.deviceId)
				let deviceId = item.deviceId
				uni.createBLEConnection({
					deviceId: deviceId,
					complete(res) {
						if (res.errMsg == "createBLEConnection:ok") {
							console.log("连接蓝牙-[" + item.name + "]--成功")
							that.connId = deviceId;
							that.deviceId = deviceId;
							that.currDev = item
							uni.showToast({
								title: '连接成功',
								icon: 'success',
								duration: 2000
							})
						} else {
							console.log(res)
						}
						//连接成功 关闭搜索
						that.stopFindBule()
					},
				})

			},
			getWeight(){
		      var that = this
			  let deviceId = that.deviceId;
			  // 获取服务
			  uni.getBLEDeviceServices({
				deviceId: deviceId,
				success: function(res) {
				  // 获取特征
				  res.services.forEach(function(service) {
					uni.getBLEDeviceCharacteristics({
					  deviceId: deviceId,
					  serviceId: service.uuid,
					  success: function(res) {
						// 输出serviceId和characteristicId
						res.characteristics.forEach(function(characteristic) {
						  //订阅电子秤的数值变化（需要知道特征值(UUID)）
						  uni.notifyBLECharacteristicValueChange({
							state: true,
							deviceId: deviceId,
							serviceId: service.uuid,
							characteristicId: characteristic.uuid,
							success: (res) => {
							  console.log('订阅成功', res);
								  // 监听数据变化
									uni.onBLECharacteristicValueChange((res) => {
										//获取到的蓝牙秤返回的值不是十进制的数字，需要进行转换
										// 解析接收到的数据
										var www = that.hexCharCodeToStr(that.buf2hex(res.value));
										// console.log('www:', Number(www));
										let oldVal = that.form.realWeight;
										that.form.realWeight = Number(www);
										that.wd(that.form.realWeight,oldVal);
									});
							},
							fail: (err) => {
							  console.error('订阅失败', err);
							},
							complete: (res) => {
							  console.log('订阅结果', res);
							},
							});
						});
					  }
					});
				  });
				}
			  });
			},
			//断开蓝牙
			closeBLEConnection() { // 这个是断开蓝牙
				uni.closeBLEConnection({
					deviceId: this.deviceId,
					success(res) {
						console.log('关闭成功', res)
					},
					fail(res) {
						console.log('关闭失败', res)
					}
				})
			}
		}
	}
</script>
